﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Cashier_Service;
using Cashier_Interface;
using Cashier_Utils;
using Cashier.utils;
using Cashier.shipment;

namespace Cashier.finance
{
    public partial class BillShipmentRepaymentControl : UserControl, IDataGridViewData, IReloadData, IPrinter
    {
        private MainForm mainform;
        private static BillShipmentRepaymentControl shipmentRepaymentControl;
        private BillShipmentRepaymentService repaymentService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        private BillShipmentRepaymentControl(MainForm mainform)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.dataGridView1.ImplementsInstance = this;
            this.repaymentService = new BillShipmentRepaymentService();

            this.ControlsSetRights();
            this.Dock = DockStyle.Fill;
        }

        /// <summary>
        /// 返回BillShipmentRepaymentControl实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <returns></returns>
        public static BillShipmentRepaymentControl GetBillShipmentRepaymentControl(MainForm mainform, String shipmentno)
        {
            if (shipmentRepaymentControl == null)
                shipmentRepaymentControl = new BillShipmentRepaymentControl(mainform);

            if (!String.IsNullOrEmpty(shipmentno))
                shipmentRepaymentControl.textbox_shipmentno.Text = shipmentno;
            shipmentRepaymentControl.RefreshDataGridViewData();
            return shipmentRepaymentControl;
        }

        #region 功能方法实现

        /// <summary>
        /// 控件设置权限
        /// </summary>
        private void ControlsSetRights()
        {
            Button[] buttons = { button_query, button_repayment };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
            ContextMenuStrip[] menuStrips = { contextMenuStrip_dgv };
            RightsforControls.RightsforContextMenuStrip(mainform.Admin.RolePurviewtable, menuStrips);
        }

        /// <summary>
        /// 查询出货单商品
        /// </summary>
        private void ViewShipmentGoods()
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                String shipmentno = dataGridView1.SelectedRows[0].Cells["shipment_no"].Value.ToString();
                ShipmentGoodsListControl goodsListControl = ShipmentGoodsListControl.GetShipmentGoodsListControl(mainform, shipmentno);
                mainform.AddDataGridViewPanelControl(goodsListControl);
            }
        }

        /// <summary>
        /// 打开还款窗口
        /// </summary>
        private void ShowRepaymentForm()
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                DataGridViewRow dgvRow = dataGridView1.SelectedRows[0];
                decimal debtAmount = (decimal)dgvRow.Cells["remain_amount"].Value;
                DebtBillShipmentAddForm shipmentAddForm = new DebtBillShipmentAddForm(mainform, dataGridView1.SelectedRows[0], debtAmount, this);
                shipmentAddForm.ShowDialog();
            }
        }

        /// <summary>
        /// 删除还款记录
        /// </summary>
        private void DeleteRepayment()
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                DialogResult result = MessageBox.Show("确定要删除还款记录吗？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                    {
                        sb.Append(row.Cells["id"].Value.ToString()).Append(",");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    int count = repaymentService.DeleteBillShipmentRepayment(sb.ToString());
                    if (count > 0)
                    {
                        MessageBox.Show("删除成功！");
                        this.RefreshDataGridViewData();
                    }
                    else
                        MessageBox.Show("删除失败！");
                }
            }
        }

        #endregion

        #region IDataGridViewData 成员

        void IDataGridViewData.EnterkeyEventHandler()
        {
            return;
        }

        void IDataGridViewData.GenerateGridViewColumns(DataGridView dgv)
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("shipment_no", "出货单号", true, 18, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("member_no", "客户编号", true, 14, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("member_name", "客户名称", true, 10, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("shipment_total", "货单总金额", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("debt_amount", "欠款金额", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("pay_amount", "还款金额", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("give_amount", "找零金额", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("remain_amount", "余欠金额", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("admin_name", "收款人", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("repayment_date", "收款日期", true, 10, ActKey.CENTER, ActKey.CENTER, true, false));
        }

        void IDataGridViewData.GetBindingData(int rowindex, int pageindex, int pagesize)
        {
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String adminUsername = mainform.UsernameForQuery;
                String shipmentno = textbox_shipmentno.Text.Trim();
                String memberno = textbox_memberno.Text.Trim();

                DataTable dt = this.repaymentService.GetBillShipmentRepaymentTable(pageindex, pagesize, enterpriseNo,
                    shipmentno, memberno, adminUsername, null, "id");
                this.dataGridView1.DataSource = dt;
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (rowindex > 0)
                        dataGridView1.Rows[0].Selected = false;
                    dataGridView1.Rows[rowindex].Selected = true;
                }
                dataGridView1.Columns[0].Visible = false;

                mainform.SetPageInfo(dataGridView1.Recordcount, pageindex, pagesize);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        long IDataGridViewData.GetBindingDataRecord()
        {
            long record = 0;
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String adminUsername = mainform.UsernameForQuery;
                String shipmentno = textbox_shipmentno.Text.Trim();
                String memberno = textbox_memberno.Text.Trim();

                record = this.repaymentService.GetBillShipmentRepaymentRecord(enterpriseNo, shipmentno, memberno, adminUsername);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return record;
        }

        #endregion

        #region 刷新数据

        /// <summary>
        /// 刷新数据
        /// </summary>
        public void RefreshDataGridViewData()
        {
            this.dataGridView1.LoadingData();
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 查询事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_query_Click(object sender, EventArgs e)
        {
            this.RefreshDataGridViewData();
        }

        /// <summary>
        /// 查看出货单商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_view_Click(object sender, EventArgs e)
        {
            this.ViewShipmentGoods();
        }

        /// <summary>
        /// 继续还款
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_rePayment_Click(object sender, EventArgs e)
        {
            this.ShowRepaymentForm();
        }

        /// <summary>
        /// 删除还款记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_delete_Click(object sender, EventArgs e)
        {
            this.DeleteRepayment();
        }

        #endregion

        #region 重写方法

        /// <summary>
        /// 重写键盘事件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            if (keyData == Keys.Up || keyData == Keys.Down)
            {
                this.dataGridView1.Focus();
            }
            else if (keyData == Keys.F8)
            {
                this.RefreshDataGridViewData();
            }
            else if (keyData == Keys.F9)
            {
                this.ShowRepaymentForm();
            }
            return b;
        }

        #endregion

        #region IReloadData 重成加载数据 成员

        void IReloadData.ReloadDataGridViewData(object param)
        {
            this.RefreshDataGridViewData();
        }

        #endregion


        #region IPrinter 成员

        /// <summary>
        /// 打印所有数据
        /// </summary>
        /// <returns></returns>
        DataGridView IPrinter.GetAllRows()
        {
            try
            {
                ((IDataGridViewData)this).GetBindingData(0, 0, 0);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return this.dataGridView1;
        }

        /// <summary>
        /// 打印选择数据
        /// </summary>
        /// <returns></returns>
        DataGridView IPrinter.GetSelectedRows()
        {
            return this.dataGridView1;
        }

        /// <summary>
        /// 显示隐藏列
        /// </summary>
        /// <param name="columnname"></param>
        void IPrinter.VisibleColumn(string columnname)
        {
            try
            {
                if (this.dataGridView1.Columns[columnname].Visible)
                    this.dataGridView1.Columns[columnname].Visible = false;
                else
                    this.dataGridView1.Columns[columnname].Visible = true;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        #endregion
    }
}
